<template>
    <div>
<!--       搜索框 -->
        <el-row>
            <el-col :span="8">
                <el-input placeholder="请输入内容" clearable v-model="queryInfo.queryString" class="input-with-select" @clear="findPage">
                    <el-button slot="append" icon="el-icon-search" @click="findPage"/>
                </el-input>
            </el-col>
            <el-col :span="2">
                <el-button style="margin-left: 10px"  @click="insert" type="primary">添加信息</el-button>
            </el-col>
        </el-row>
        
        
<!--        展示列表-->
        <el-table :data="tableList" stripe >
            <el-table-column prop="id" label="主键" width="180"/>
            <el-table-column prop="label" label="角色标签" width="180"/>
            <el-table-column prop="code" label="角色代码"/>
            <el-table-column label="是否启用" v-hasPermi="['PRE_UPDATE']">
                <template slot-scope="scope">
                    <el-switch @change="updateStatus(scope.row)" v-model="scope.row.status" />
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="180">
                <template slot-scope="scope">
                    <el-button type="primary" @click="update(scope.row) "  size="small" icon="el-icon-edit" circle/>
                    <el-button type="danger" @click="deleteById(scope.row.id)" size="small"   icon="el-icon-delete" circle/>
                </template>
            </el-table-column>
        </el-table>
        
        
<!--        分页展示-->
        <el-pagination
            @size-change="handlePageSize"
            @current-change="handlePageNumber"
            :current-page="currentPage4"
            :page-sizes="[7, 25, 50, 100]"
            :page-size="queryInfo.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"/>
        
<!--        添加和修改弹框-->
        <el-dialog class="dialog" :title="title" :visible.sync="open1" width="40%" @close="clickCancel">
            <el-form :model="form" ref="form" :rules="rules">
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="角色标签" prop="label">
                            <el-input v-model="form.label" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="角色代码" prop="code">
                            <el-input v-model="form.code"  />
                        </el-form-item>
                    </el-col>
                    <el-col :span="23">
                        <el-card>
                            <div slot="header" class="clearfix">
                                <span>菜单信息</span>
                            </div>
                                <el-tree
                                    ref="tree"
                                    check-strictly
                                    highlight-current
                                    :data="menuList"
                                    show-checkbox
                                    node-key="id"
                                    :props="{label:'title',children:'children'}"
                                    @check-change="treeChange"
                                />
                        </el-card>
                    </el-col>
                    <el-col :span="23">
                        <el-card>
                            <div slot="header" class="clearfix">
                                <span>权限信息</span>
                            </div>
                            <el-checkbox-group v-model="checkPermis" >
                                <el-checkbox
                                    
                                    border
                                    size="small"
                                    v-for="(permission,index) in permissionList"
                                    :disabled="!permission.status"
                                    :label="permission.label"
                                    :key="index"
                                    @change="getPermissions(permission)"
                                />
                              
                            </el-checkbox-group>
                        </el-card>
                    </el-col>
                    <el-col>
                        <el-form-item label="是否启用" prop="status" >
                            <el-radio-group v-model="form.status">
                                <el-radio :label="true">是</el-radio>
                                <el-radio :label="false">否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="clickCancel">取 消</el-button>
                <el-button type="primary" @click="clickOk">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            //分页查询条件
            queryInfo: {
                //页码
                pageNumber: 1,
                //页数
                pageSize: 7,
                //关键字
                queryString: ""
            },
            //表格数据
            tableList:[],
            //总记录数
            total: 0,
            
            currentPage4: 1,
            //弹窗标题
            title: null,
            //是否打开会话框
            open1: false,
            //表单数据
            form: {
                status: true
            },
            //表单校验
            rules:{
                label:[
                    { required: true, message: '请输入角色标签', trigger: 'blur' },
                    {min:1 , max: 50, message: "角色标签的长度为1~50",trigger: 'blur'}
                ],
                code:[
                    { required: true, message: '请输入角色标签值', trigger: 'blur' },
                    {min:1 , max: 20, message: "角色标签值的长度为1~20",trigger: 'blur'}
                ]
            },
            //从后端获取的菜单和权限数据
            menuList: [],
            permissionList: [],
            //被选中的菜单和权限数据
            checkMenus: [],
            checkPermis: [],
            checkPermissions: [],
        }
    },
    methods:{
        /*获取所选中的权限*/
        getPermissions(permission){
            this.checkPermissions.push(permission);
        },
        
        /*菜单树形控件 节点值被选中 */
        treeChange(){
            this.checkMenus = [];
            //getCheckedNodes：获取tree控件中选中的值得控件
            //第一个参数：是否获取父节点的数据
            //第二个参数：当check-strictly为false的情况下，是否包含半选节点的数据，选子节点，是否包含父节点
            const checks = this.$refs.tree.getCheckedNodes(false,true);
            checks.forEach(item =>{
               this.checkMenus.push(item);
            });
        },
        
        
        /*****************************/
    
    
        /*关闭弹窗表单时刷新表单数据*/
        clickCancel(){
            this.checkPermissions = [];
            this.checkPermis = [];
            this.$refs.tree.setCheckedKeys([]);
            this.form = { status: true};
            this.open1 = false;
            this.checkMenus = [];
        },
    
        //提交表单要添加的角色数据给后端
        clickOk(){
            //进行表单校验
            this.$refs.form.validate((valid) =>{
                //校验不通过
                if(!valid) return this.$message.error('表单校验不通过，请检查后提交！')
                
                this.form.menus = this.checkMenus;
                this.form.permissions = this.checkPermissions;
                //校验通过 判断是否是新增
                if(this.form.id === undefined || this.form.id ===null){
                    this.$ajax.post("/role/insert",this.form).then((res)=>{
                        this.$message.success(res.data.message)
                        this.open1 = false;
                        this.findPage();
                    })
                }else {
                    this.$ajax.put('/role/update',this.form).then((res)=>{
                        this.$message.success(res.data.message)
                        this.open1 = false;
                        this.findPage();
                    })
                }
            })
        },
    
        /****************************/
    
        /*查询所有的菜单和权限信息并添加到弹窗中*/
        findMenusAndPermission(){
          this.$ajax.get("/menu/findParent").then(res =>{
              this.menuList = res.data.data;
              
              /*****1.需要修改*******/
              this.menuList.filter((item)=>{
                  item.disabled = !item.status;
                  if (item.children && item.children.length >0){
                      item.children.filter((item2)=>{
                          item2.disabled= !item2.status
                      })
                  }
                  return true;
              });
              console.log("可供选择的菜单信息",this.menuList);
          });
          
          this.$ajax.get("/permission/select").then(res =>{
             this.permissionList = res.data.data;
              console.log("可供选择的权限信息",this.permissionList);
          });
          
        },
        
        /****************************/
        /*添加角色信息*/
        insert(){
            this.title = "添加角色";
            this.open1 = true;
        },
        /*删除角色信息*/
        deleteById(id){
            this.$confirm('您将永久删除id是{' + id +' }的角色, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //调用后端删除角色接口
                this.$ajax.delete(`/role/delete/${id}`).then(res => {
                    this.$message.success(res.data.message);
                    this.queryInfo.pageNumber = 1;
                    this.findPage();
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        /*修改角色信息*/
        update(row){
            this.form = row;
            this.title = "修改角色";
            this.checkMenus = [];
            this.checkPermis = [];
            row.menus.forEach(item =>{
                this.checkMenus.push(item);
                if (item.children && item.children.length >0){
                    item.children.forEach(i =>{
                       this.checkMenus.push(i);
                    });
                }
            });
            
            row.permissions.forEach(item =>{
                this.checkPermis.push(item.label);
            })
            //添加异步方法
            this.$nextTick(()=>{
                this.$refs.tree.setCheckedNodes(this.checkMenus)
            })
            this.open1 = true;
        },
        /*改变角色数据的状态*/
        updateStatus(row){
            this.$ajax.put('/role/update',row).then((res)=>{
                this.$message.success("状态更新成功！")
            })
        },
        /*分页查询角色信息*/
        findPage(){
            this.$ajax.post("/role/findPage", this.queryInfo).then((res)=>{
                this.tableList = res.data.rows;
                console.log("查询角色返回数据",res.data.rows);
                this.total = res.data.total;
            });
        },
        /*页面改变事件*/
        handlePageNumber(newPageNumber){
            //将分页的新数据的参数传递给后端查询
            this.queryInfo.pageNumber = newPageNumber;
            //调分页方法
            this.findPage();
        },
        handlePageSize(newPageSize){
            this.queryInfo.pageSize = newPageSize;
            this.findPage();
        },
    },
    
    created(){
        this.findPage();
        this.findMenusAndPermission();
    },
};
</script>

<style scoped>
.el-col{
    margin-left: 20px;
}

.el-checkbox-group{
    text-align: left;
}
.el-checkbox{
    margin-right: 10px;
    margin-bottom: 10px;
}
.dialog{
    text-align: left;
}
</style>